package com.xfy.jwtdemo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import jdk.nashorn.internal.parser.Token;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xft
 * @date 2018/3/17  9:52
 */
public class JwtToken {
    /**
     * 公用秘钥-保存在服务端，客户端是不会知道秘钥的，以防被攻击
     */
    public static String SECRET = "FUCK";

    /**
     * 生成token
     *
     * @return
     * @throws Exception
     */
    public static String createToken() throws Exception {
        //签发时间
        Date iatDate = new Date();

        //设置1分钟过期时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 1);
        Date expiresDate = calendar.getTime();
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        String token = JWT.create()
                .withHeader(map)//header
                .withClaim("name", "FUCK")//payload
                .withClaim("age", 21)
                .withClaim("org", "今日头条")
                .withExpiresAt(expiresDate)//设置过期时间,过期时间要大于签发时间
                .withIssuedAt(iatDate)//设置签发时间
                .sign(Algorithm.HMAC256(SECRET));//加密
        return token;
    }

    /**
     * 解密token
     * @param token
     * @return
     * @throws Exception
     */
    public static Map<String, Claim> verifyToken(String token) throws Exception {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT jwt = null;
        try {
            jwt = verifier.verify(token);
        } catch (Exception e) {
            throw new RuntimeException("登陆凭证已过期，请重新登陆");
        }
        return jwt.getClaims();
    }

}
